package com.handa.documentManager.utils;

import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.regex.Pattern;

@Component
public class BucketNameGenerator {

    private static final String LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
    private static final String NUMBERS = "0123456789";
    private static final String ALLOWED_SPECIAL_CHARS = ".-";
    private static final String ALL_CHARACTERS = LOWER_CASE_LETTERS + NUMBERS + ALLOWED_SPECIAL_CHARS;

    private static final int MIN_LENGTH = 10;
    private static final int MAX_LENGTH = 25;

    private static final Pattern IP_ADDRESS_PATTERN = Pattern.compile(
            "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
    );

    private final Random random = new Random();

    /**
     * 生成符合MinIO bucket命名规则的随机名称
     */
    public String generateBucketName() {
        String bucketName;
        int attempts = 0;
        int maxAttempts = 100;

        do {
            // 生成长度在3-63之间的随机名称
            int length = random.nextInt(MAX_LENGTH - MIN_LENGTH + 1) + MIN_LENGTH;
            bucketName = generateRandomString(length);
            attempts++;

            // 防止无限循环
            if (attempts > maxAttempts) {
                throw new IllegalStateException("无法生成有效的bucket名称，请检查生成逻辑");
            }

        } while (!isValidBucketName(bucketName));

        return bucketName;
    }

    /**
     * 生成指定长度的随机字符串
     */
    private String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            char c = ALL_CHARACTERS.charAt(random.nextInt(ALL_CHARACTERS.length()));
            sb.append(c);
        }

        return sb.toString();
    }

    /**
     * 验证bucket名称是否符合所有规则
     */
    public boolean isValidBucketName(String bucketName) {
        // 检查长度
        if (bucketName.length() < MIN_LENGTH || bucketName.length() > MAX_LENGTH) {
            return false;
        }

        // 检查字符组成
        if (!bucketName.matches("^[a-z0-9.-]+$")) {
            return false;
        }

        // 检查相邻的特殊字符
        if (bucketName.contains("..") || bucketName.contains(".-") ||
                bucketName.contains("-.") || bucketName.contains("--")) {
            return false;
        }

        // 检查IP地址格式
        if (IP_ADDRESS_PATTERN.matcher(bucketName).matches()) {
            return false;
        }

        // 检查前缀
        if (bucketName.startsWith("xn--")) {
            return false;
        }

        // 检查后缀
        if (bucketName.endsWith("-s3alias")) {
            return false;
        }

        // 检查首尾字符（不能是特殊字符）
        char firstChar = bucketName.charAt(0);
        char lastChar = bucketName.charAt(bucketName.length() - 1);
        if (firstChar == '.' || firstChar == '-' ||
                lastChar == '.' || lastChar == '-') {
            return false;
        }

        return true;
    }

    /**
     * 批量生成bucket名称
     */
    public String[] generateBucketNames(int count) {
        String[] names = new String[count];
        for (int i = 0; i < count; i++) {
            names[i] = generateBucketName();
        }
        return names;
    }
}